package com.example.ayniu.treadmill;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ayniu.treadmill.base.BaseActivity;
import com.example.ayniu.treadmill.base.blueInterface;
import com.example.ayniu.treadmill.bluetooth.BluetoothChatService;

//import java.util.HashMap;
//import java.util.Map;
//import org.apache.http.util.EncodingUtils;

public class ClassActivity extends BaseActivity {

    private ImageView img_turnback;
    private WebView mWebView;
    private CountDownTimer mCountDownTimer;     //开始前的倒计时
    private TextView tv_countdown;
    private RelativeLayout layout_countdown;
    private RelativeLayout layout_class;          //课程进行的界面
    private RelativeLayout layout_start_tip,layout_stop_tip;
    private Button bt_start_class,bt_stop_class;
    private Button bt_tip_start,bt_tip_goon,bt_tip_stop;
    MainActivity mainActivity = (MainActivity)MainActivity.mainInstance;    //获取MainActivity

    public static TextView class_data_distance,class_data_calories,class_data_speed,class_data_time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class);

        //获取选择的课程参数值，便于网页匹配课程
        Intent intent = getIntent();
        int VALUE_CLASS = intent.getExtras().getInt("VALUE_CLASS");
        //Toast.makeText(this, "课程参数："+VALUE_CLASS, Toast.LENGTH_LONG).show();

        initView();
    }

    public void initView(){
        img_turnback = (ImageView)findViewById(R.id.imgclass_turnback);
        img_turnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        Intent intent = getIntent();
        int VALUE_CLASS = intent.getExtras().getInt("VALUE_CLASS");
        String urlCourse = "http://mp.beatwalker.cn/mp/html/customizedcourses1.html";
        //String postData = "CourseNo=T01";
        if((VALUE_CLASS & 31) == 1)
        {
            urlCourse = "http://mp.beatwalker.cn/mp/html/customizedcourses1.html";
        }
        else if((VALUE_CLASS & 31) == 2)
        {
            urlCourse = "http://mp.beatwalker.cn/mp/html/customizedcourses2.html";
        }
        else if((VALUE_CLASS & 31) == 4)
        {
            urlCourse = "http://mp.beatwalker.cn/mp/html/customizedcourses3.html";
        }
        else if((VALUE_CLASS & 31) == 8)
        {
            urlCourse = "http://mp.beatwalker.cn/mp/html/customizedcourses4.html";
        }

        //Map<String, String > map = new HashMap<String, String>();
        //map.put("CourseNo", "T01");

        mWebView.loadUrl(urlCourse);
        //mWebView.postUrl(urlCourse, EncodingUtils.getBytes(postData, "base64"));
        //mWebView.loadUrl(urlCourse, map);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开

        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });

        class_data_distance = (TextView) findViewById(R.id.data_class_distance);
        class_data_calories = (TextView) findViewById(R.id.data_class_calories);
        class_data_time = (TextView) findViewById(R.id.data_class_time);
        class_data_speed = (TextView) findViewById(R.id.data_class_speed);

        bt_start_class = (Button) findViewById(R.id.bt_start_class);
        bt_stop_class = (Button) findViewById(R.id.bt_stop_class);
        bt_tip_start = (Button) findViewById(R.id.bt_tip_start);
        bt_tip_goon = (Button) findViewById(R.id.bt_tip_goon);
        bt_tip_stop = (Button) findViewById(R.id.bt_tip_stop);

        layout_class = (RelativeLayout) findViewById(R.id.layout_class);
        layout_class.setVisibility(View.GONE);
        layout_start_tip = (RelativeLayout) findViewById(R.id.layoutclass_start_tip);
        layout_stop_tip = (RelativeLayout) findViewById(R.id.layoutclass_stop_tip);

        bt_start_class.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_start_tip.setVisibility(View.VISIBLE);
            }
        });
        bt_stop_class.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_stop_tip.setVisibility(View.VISIBLE);
                handler.removeCallbacks(runnable);//暂停线程
            }
        });

        bt_tip_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_start_tip.setVisibility(View.GONE);
                mCountDownTimer.start();
            }
        });
        bt_tip_goon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.post(runnable);//继续运动界面数据更新
                layout_stop_tip.setVisibility(View.GONE);
            }
        });
        bt_tip_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(runnable);//暂停线程
                //向设备请求运动参数(A)
                blueInterface blueI = new blueInterface();
                blueInterface.stopReq stopReq = blueI.new stopReq();
                stopReq.msgType = 0;
                //stopReq.usRes = 0;
                byte[] sendData = new byte[512];
                int sendLength = stopReq.createFrame(sendData);
                byte[] realSend = new byte[sendLength];
                sendLength = stopReq.createFrame(realSend);
                sendMessage(realSend, sendLength);
                ClassActivity.this.finish();
            }
        });

        layout_countdown = (RelativeLayout) findViewById(R.id.layoutclass_countdown);
        tv_countdown = (TextView)findViewById(R.id.tvclass_countdown);

        //开始倒计时的实现
        mCountDownTimer = new CountDownTimer(4000, 1000) {
            int i = 3;
            @Override
            public void onTick(long millisUntilFinished) {
                layout_countdown.setVisibility(View.VISIBLE);
                tv_countdown.setText(i+"");
                if(i == 3) {
                    blueInterface blueI = new blueInterface();
                    blueInterface.startReq startReq = blueI.new startReq();
                    startReq.msgType = 0;
                    startReq.workType = 0; // 0 nalmal 2 course
                    Intent intent = getIntent();
                    int VALUE_CLASS = intent.getExtras().getInt("VALUE_CLASS");
                    String cmd = "10,20,VS00011;15,40,;300,,VA00042;260,15,VB0101;";
                    if((VALUE_CLASS & 31) == 1)
                    {
                        cmd = "10,15,VS00011;20,25,;5,35,VA00042;10,45,VB0101;";
                    }
                    else if((VALUE_CLASS & 31) == 2)
                    {
                        cmd = "20,20,VS00011;20,40,;30,,VA00042;30,15,VB0101;";
                    }
                    else if((VALUE_CLASS & 31) == 4)
                    {
                        cmd = "30,20,VS00011;90,40,;25,,VA00042;30,19,VB0101;";
                    }
                    else if((VALUE_CLASS & 31) == 8)
                    {
                        cmd = "80,20,VS00011;80,40,;120,,VA00042;360,15,VB0101;";
                    }
                    byte cmdByte[] = cmd.getBytes();
                    int j;
                    for(j = 0; j < cmd.length(); j++)
                    {
                        startReq.courseName[j] = cmdByte[j];
                    }
                    startReq.courseName[j] = 0;

                    byte[] sendData = new byte[512];
                    int sendLength = startReq.createFrame(sendData);
                    byte[] realSend = new byte[sendLength];
                    sendLength = startReq.createFrame(realSend);
                    sendMessage(realSend, sendLength);
                }
                i--;
                dimBackground(1.0f,0.5f);
            }
            @Override
            public void onFinish() {
                i = 3;
                dimBackground(0.5f,1.0f);
                mCountDownTimer.cancel();
                layout_countdown.setVisibility(View.GONE);
                layout_class.setVisibility(View.VISIBLE);
                //向设备发出开始运动的请求(A)
                /*
                blueInterface blueI = new blueInterface();
                blueInterface.startReq startReq = blueI.new startReq();
                startReq.msgType = 0;
                startReq.workType = 0; // 0 nalmal 2 course
                Intent intent = getIntent();
                int VALUE_CLASS = intent.getExtras().getInt("VALUE_CLASS");
                String cmd = "10,20,VS00011;15,40,;300,,VA00042;260,15,VB0101;";
                if((VALUE_CLASS & 31) == 1)
                {
                    cmd = "10,15,VS00011;20,25,;5,35,VA00042;10,45,VB0101;";
                }
                else if((VALUE_CLASS & 31) == 2)
                {
                    cmd = "20,20,VS00011;20,40,;30,,VA00042;30,15,VB0101;";
                }
                else if((VALUE_CLASS & 31) == 4)
                {
                    cmd = "30,20,VS00011;90,40,;25,,VA00042;30,19,VB0101;";
                }
                else if((VALUE_CLASS & 31) == 8)
                {
                    cmd = "80,20,VS00011;80,40,;120,,VA00042;360,15,VB0101;";
                }
                byte cmdByte[] = cmd.getBytes();
                int j;
                for(j = 0; j < cmd.length(); j++)
                {
                    startReq.courseName[j] = cmdByte[j];
                }
                startReq.courseName[j] = 0;

                byte[] sendData = new byte[512];
                int sendLength = startReq.createFrame(sendData);
                byte[] realSend = new byte[sendLength];
                sendLength = startReq.createFrame(realSend);
                sendMessage(realSend, sendLength);
                */
                handler.post(runnable);//开启运动界面数据更新
            }
        };
    }

    //实现数据随运动时间而动态更新
    public android.os.Handler handler = new android.os.Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //向设备请求运动参数(A)
            blueInterface blueI = new blueInterface();
            blueInterface.paraGetReq paraGetReq = blueI.new paraGetReq();
            //paraGetReq.usRes = ;
            byte[] sendData = new byte[512];
            int sendLength = paraGetReq.createFrame(sendData);
            byte[] realSend = new byte[sendLength];
            sendLength = paraGetReq.createFrame(realSend);
            sendMessage(realSend, sendLength);

            handler.postDelayed(runnable, 1000);
        }
    };

    /**
     * 发送数据到设备的方法
     * @param message  A string of text to send.
     */
    public void sendMessage(byte[] message, int length) {
        // Check that we're actually connected before trying anything
        if (MainActivity.mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (length > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            MainActivity.mChatService.write(message);
            // Reset out string buffer to zero and clear the edit text field
            MainActivity.mOutStringBuffer.setLength(0);
            Log.i("sendMessage", "send: " + message);
        }
    }

    //屏幕变暗的实现方法
    private void dimBackground(final float from, final float to) {
        final Window window = this.getWindow();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                WindowManager.LayoutParams params = window.getAttributes();
                params.alpha = (Float) animation.getAnimatedValue();
                window.setAttributes(params);
            }
        });
        valueAnimator.start();
    }
}
